package com.socialuni.center.web.serive.talk;

import com.socialuni.sdk.api.model.QO.talk.SocialHomeTalkQueryQO;
import com.socialuni.sdk.api.model.RO.talk.SocialTalkRO;
import com.socialuni.center.web.factory.CenterTalkROFactory;
import com.socialuni.center.web.utils.CenterUserUtil;
import com.socialuni.center.web.utils.DevAccountUtils;
import com.socialuni.center.web.utils.UnionIdDbUtil;
import com.socialuni.sdk.constant.GenderTypeQueryVO;
import com.socialuni.sdk.constant.TalkTabType;
import com.socialuni.sdk.exception.SocialParamsException;
import com.socialuni.sdk.model.DO.user.UserDO;
import com.socialuni.sdk.model.RectangleVO;
import com.socialuni.sdk.platform.AliAPI;
import com.socialuni.sdk.repository.TalkRepository;
import com.socialuni.sdk.service.talk.SocialQueryFollowUserTalksService;
import com.socialuni.sdk.service.talk.SocialQueryHomeTalksService;
import com.socialuni.sdk.store.SocialHomeTalksQueryStore;
import com.socialuni.sdk.store.TalkQueryStore;
import com.socialuni.sdk.utils.GenderUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @author qinkaiyuan
 * @date 2020-05-16 20:11
 */
@Service
@Slf4j
public class CenterQueryHomeTalksService {
    @Resource
    private TalkRepository talkRepository;
    @Resource
    private TalkQueryStore talkQueryStore;
    //    @Resource
//    private TagService tagService;
    @Resource
    private SocialHomeTalksQueryStore socialHomeTalksQueryStore;
    @Resource
    SocialQueryFollowUserTalksService socialQueryFollowUserTalksService;
    @Resource
    SocialQueryHomeTalksService socialQueryHomeTalksService;

    public List<SocialTalkRO> queryHomeTalks(SocialHomeTalkQueryQO queryVO) {
        String appGenderType = DevAccountUtils.getAppGenderType();
        UserDO mineUser = CenterUserUtil.getMineUser();
        //获取自己的user
//        log.info("getListResultVO开始：" + new Date().getTime() / 1000);
        //入参兼容处理
        this.disposeTalkQueryVO(queryVO);
        //校验入参正确
        //校验tab类型
        String tabType = queryVO.getTabType();
        if (!TalkTabType.values.contains(tabType)) {
            throw new SocialParamsException("错误的tab类型");
        }

        //根据id查询
        log.debug("开始查询：" + new Date().getTime() / 1000);
        List<Integer> talkIds =  UnionIdDbUtil.getContentIdsByTalkUnionIds(queryVO.getTalkIds());
//        List<Integer> talkIds = new ArrayList<>();
//        List<Integer> talkIds = queryVO.getTalkIds();
        log.debug("获取所有id查询：" + new Date().getTime() / 1000);
        //逻辑
        //sql 需要特殊处理,sql中使用了not in 所以不能为空数组
        if (talkIds.size() == 0) {
            talkIds = new ArrayList<>(Collections.singletonList(0));
        }
        queryVO.setTabType(tabType);

        List<SocialTalkRO> talkDOS;
        //为关注，查询关注
        if ((TalkTabType.follow_type.equals(tabType))) {
            talkDOS = socialQueryFollowUserTalksService.queryUserFollowTalks(talkIds, mineUser);
        } else {
            talkDOS = this.queryHomeTalks(talkIds, queryVO, mineUser, appGenderType);
        }
        //返回结果转vo

        //生成加密id
        log.debug("进入：" + new Date().getTime() / 1000);


        log.debug("开始数据库查询2：" + new Date().getTime() / 1000);
        if ((queryVO.getLon() == null || queryVO.getLat() == null)) {
            //调用网络接口40毫秒
            RectangleVO rectangleVO = AliAPI.getRectangle();
            if (rectangleVO != null) {
                queryVO.setLon(rectangleVO.getLon());
                queryVO.setLat(rectangleVO.getLat());
            }
        }
//        log.debug("开始转换vo" + new Date().getTime() / 1000);
        List<SocialTalkRO> socialTalkROFactories = CenterTalkROFactory.newHomeCommentROS(talkDOS);
//        log.debug("返回结果：" + new Date().getTime() / 1000);
//        log.info("getListResultVO结束：" + new Date().getTime() / 1000);
        return socialTalkROFactories;
    }




    /*public List<TalkDO> queryStickTalks() {
        Integer devId = DevAccountUtils.getDevId();
        if (devId == null) {
            devId = AppConfigConst.qingchiDevId;
        }
        return talkRepository.findTop2ByStatusAndDevIdAndGlobalTopGreaterThanOrderByGlobalTopDesc(ContentStatus.enable, DevAccountUtils.getDevId(), CommonConst.initNum);
    }*/

    //查询非关注tab的动态列表
    public List<SocialTalkRO> queryHomeTalks(List<Integer> talkIds, SocialHomeTalkQueryQO queryVO, UserDO user, String appGenderType) {
//        log.info("queryNotFollowTalks开始1：" + new Date().getTime() / 1000);
        List<SocialTalkRO> stickTalks = new ArrayList<>();
        /*if (talkIds.size() == 1 && talkIds.get(0).equals(0)) {
            stickTalks = this.queryStickTalks();
        }*/

        //入参版本兼容处理
        this.homeTalksQOCompatible(queryVO, appGenderType);

        String queryGenderType = queryVO.getTalkVisibleGender();

        //校验gender类型
        //获取genderType对应的userGender和talkGender
        GenderTypeQueryVO genderTypeQueryVO = GenderUtil.checkQueryGenderType(queryGenderType);
        //无限制，所有人都可以查询，女生和男生发布的。
        String talkVisibleGender = genderTypeQueryVO.getTalkVisibleGender();

        //校验talk可见类型是否与appgender类型一致，还有与usergender类型一致


        GenderUtil.checkAppAndVisibleGender(appGenderType, talkVisibleGender, user == null ? null : user.getGender());

        queryVO.setUserGender(genderTypeQueryVO.getUserGender());
        queryVO.setTalkVisibleGender(talkVisibleGender);


        //更新话题使用次数
//        ResultRO<Set<TagDO>> resultRO = tagService.checkAndUpdateTagCount(user, tagIds, TalkOperateType.talkQuery, talkVisibleGender);
//        if (resultRO.hasError()) {
//            return new ResultRO<>(resultRO.getErrorMsg());
//        }

        List<SocialTalkRO> talkDOS = socialQueryHomeTalksService.queryHomeTalks(talkIds, queryVO, user);
        stickTalks.addAll(talkDOS);
        /*if (stickTalks.size() > 10) {
            stickTalks = stickTalks.subList(0, 10);
        }*/
//        log.info("queryNotFollowTalks结束1：" + new Date().getTime() / 1000);
        return stickTalks;
    }


    //兼容处理queryTalk的查询参数
    public void disposeTalkQueryVO(SocialHomeTalkQueryQO queryVO) {
        //homeType，为null，默认为首页
        //为null默认值首页
        String tabType = queryVO.getTabType();
        //新版本使用tabType，为空代表旧版本，把home_type赋值给tabType
        if (tabType == null) {
            String homeType = queryVO.getHomeType();
            //为null赋值
            if (homeType == null) {
                queryVO.setHomeType(TalkTabType.home_type);
            }
            //设置为homeType的值
            queryVO.setTabType(queryVO.getHomeType());
        }

        //talkIds，为null，默认为空数组
//        List<Integer> talkIds = queryVO.getTalkIds();
        List<Integer> talkIds = new ArrayList<>();
        //为null，默认值空数组
        if (talkIds == null) {
            queryVO.setTalkIds(new ArrayList<>());
        }
    }


    public void homeTalksQOCompatible(SocialHomeTalkQueryQO queryVO, String appGenderType) {
        //tagIds为null，默认为空数组
        //为null，默认值空数组
        List<Integer> tagIds = queryVO.getTagIds();
        if (tagIds == null || (tagIds.size() == 1 && tagIds.get(0).equals(0))) {
            queryVO.setTagIds(new ArrayList<>());
        }

        String genderType = queryVO.getTalkVisibleGender();
        //为null为旧版本,还有可能是调用时未传参
        if (genderType == null) {
            //adCode，默认为null，无需处理
            String gender = queryVO.getUserGender();
            //如果为旧版本
            String mapGender = GenderUtil.getTalkQueryGenderByOldGender(gender);

            //如果为旧版本的值，则取对应值，赋值
            if (mapGender != null) {
                queryVO.setUserGender(mapGender);
            } else if (gender == null) {
                //如果为null，则重新赋值
                //appgender不为null使用appgender
                queryVO.setUserGender(appGenderType);
            }
            queryVO.setTalkVisibleGender(queryVO.getUserGender());
        }

        //minAge
        Integer minAge = queryVO.getMinAge();
        if (minAge == null) {
            queryVO.setMinAge(0);
        }

        Integer maxAge = queryVO.getMaxAge();
        if (maxAge == null) {
            queryVO.setMaxAge(40);
        }
    }
}
